using System;
using System.Collections.Generic;
using System.Text;
using EcosimBase;
using System.Diagnostics;

namespace EcosimDemo
{
    class SampleCreature : Creature
    {
        public SampleCreature(int startX, int startY)
            : base(startX, startY)
        {
            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }

        protected override void Run()
        {
            move(randomDirection(), 50);
            foreach (Plant p in Field.Plants)
            {
                tryEat(p);
            }
        }

        protected override void Creature_HitWallEvent(HitWallEventArgs e)
        {
            if (e.Wall == Direction.Forward)
            {
                move(Direction.Backward, 100);
            }
            else if (e.Wall == Direction.Backward)
            {
                move(Direction.Forward, 100);
            }
            else if (e.Wall == Direction.Left)
            {
                move(Direction.Left, 100);
            }
            else if (e.Wall == Direction.Right)
            {
                move(Direction.Right, 100);
            }
        }

        private Direction randomDirection()
        {
            return (Direction)(new Random().Next(0, 4));
        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            StackTrace trace = new StackTrace(this.behaviorThread, true);
            System.Reflection.MethodBase method = trace.GetFrame(1).GetMethod();

            string message = String.Format("{0}.{1} : {2}",
                method.DeclaringType.FullName, method.Name, ((Exception)e.ExceptionObject).Message);

            using (System.IO.StreamWriter w = new System.IO.StreamWriter(@"C:\stack.txt"))
            {
                w.WriteLine(message);
            }

        }
    }
}
